//
//  HMUserAccountViewModel.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/11.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit
//专门处理模型相关操作

class HMUserAccountViewModel: NSObject {

    //单例
    static let shareInstance = HMUserAccountViewModel()
    
    private override init() {
    super.init()
        
        //单例的init只执行一次
        userAccount = loadUserAccount()
        
    
    }
    
    //账号模型
    var userAccount: HMUserAccount?
    //判断用户是否登录
    var userLogin: Bool{
        get {
    return userAccount != nil
        }
}
    
    
    /**
     获取accesstoken
     */
    
    func loadAccessToken(code: String,loadAcceseeTokenCallback: (error: NSError?) -> ()){
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":authorization_code,
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        //发送请求
        HMNetworkTool.sharedInstanse.POST(accessTokenString, parameters: parameters, progress: nil, success: { (task, responseObject) in
//            HMPrint("accessToken返回成功:\(responseObject)")
            //将responseObject转化为模型
            let result = responseObject as? [String:AnyObject]
            //字典转模型
            
            
            //绑定
            if let dict = result {
                self.userAccount =  HMUserAccount.init(dict: dict)
                
                //                HMPrint("转模型成功: \(userAccount)")
                self.saveUserAccount()
               
                loadAcceseeTokenCallback(error: nil)
                
//                HMPrint("地址是:\(filePath)")
            }
            
        }) { (task, error) in
            HMPrint("accessToken返回失败:\(error)")
            
            loadAcceseeTokenCallback(error: error)
        }
        
    }
        //保存账号模型
    private func saveUserAccount(){
    
        if let userAccount = self.userAccount {
            //归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
            
            
            
        }
        
        
    }
    
    //从沙盒解档对象
    func loadUserAccount() -> HMUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as?HMUserAccount
        
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //            HMPrint("没有过期: \(account)")
            return account
        }
        
        return nil
    }
    
    //MARK: - 获取用户信息
    func loadUserInfo(loadUserInfoCallback: (error: NSError?) -> ()){
    
        //守卫
        guard let access_token = userAccount?.access_token else{
        
            HMPrint("userAccount?没有值,或者access_token没有值")
            
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
            
            loadUserInfoCallback(error: error)
            return
        
        }
        
        
        guard let uid = userAccount?.uid else{
            HMPrint("userAccount?没有值,或者uid没有值")
            
            let error = HMNetworkErrorEnum.UidEmpty.error()
            
            loadUserInfoCallback(error: error)
            return
            
        }
        
        let urlSting = "https://api.weibo.com/2/users/show.json"
        
        //参数
        let parameters = [
        
        "access_token":access_token,
        "uid":uid
        ]
    
     //发送请求
        HMNetworkTool.sharedInstanse.GET(urlSting, parameters: parameters, progress: nil, success: { (task, responseObject) in
//            HMPrint("加载数据成功")
            if  let dict = responseObject as? [String: AnyObject]{
            //将或的的数据赋值给账号
              self.userAccount!.screen_name = dict["screen_name"]as?String
                
                self.userAccount!.avatar_large = dict["avatar_large"]as?String
//保存到沙盒
                self.saveUserAccount()
                //回调
                loadUserInfoCallback(error: nil)
                
             }
            
            
            }) { (task, error) in
                loadUserInfoCallback(error: error)

                
        }
    
    
    
    
    
    
    }
    
    
    
    

}
